<template>
  <div class="p-6">
    <!-- 页头 -->
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-3xl font-bold text-gray-900 dark:text-white">分类管理</h1>
        <p class="text-gray-600 dark:text-gray-400 mt-2">管理工具分类和排序</p>
      </div>
      <button
        @click="openCreateDialog"
        class="btn btn-primary flex items-center gap-2"
      >
        <Icon name="heroicons:plus" class="w-5 h-5" />
        添加分类
      </button>
    </div>

      <!-- 分类列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden">
        <div class="overflow-x-auto">
          <table class="w-full">
            <thead class="bg-gray-50 dark:bg-gray-700 border-b border-gray-200 dark:border-gray-600">
              <tr>
                <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  图标
                </th>
                <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  名称
                </th>
                <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  标识符
                </th>
                <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  描述
                </th>
                <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  排序
                </th>
                <th class="px-6 py-4 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  工具数
                </th>
                <th class="px-6 py-4 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
              <tr
                v-for="category in categories"
                :key="category.id"
                class="hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
              >
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="w-10 h-10 rounded-lg bg-gradient-to-br from-primary-100 to-purple-100 dark:from-primary-900/30 dark:to-purple-900/30 flex items-center justify-center">
                    <Icon
                      v-if="category.icon"
                      :name="category.icon"
                      class="w-6 h-6 text-primary-600 dark:text-primary-400"
                    />
                    <Icon
                      v-else
                      name="heroicons:folder"
                      class="w-6 h-6 text-gray-400"
                    />
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900 dark:text-white">
                    {{ category.name }}
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <code class="text-xs bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded text-gray-700 dark:text-gray-300">
                    {{ category.slug }}
                  </code>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-600 dark:text-gray-400 max-w-xs truncate">
                    {{ category.description || '暂无描述' }}
                  </div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 dark:bg-blue-900/30 text-blue-800 dark:text-blue-300">
                    {{ category.sortOrder }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span class="text-sm text-gray-600 dark:text-gray-400">
                    {{ category.tools?.length || 0 }} 个
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                  <div class="flex items-center justify-end gap-3">
                    <button
                      @click="openEditDialog(category)"
                      class="text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 flex items-center gap-1"
                    >
                      <Icon name="heroicons:pencil" class="w-4 h-4" />
                      编辑
                    </button>
                    <button
                      @click="deleteCategory(category)"
                      class="text-red-600 hover:text-red-700 dark:text-red-400 dark:hover:text-red-300 flex items-center gap-1"
                    >
                      <Icon name="heroicons:trash" class="w-4 h-4" />
                      删除
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页 -->
        <Pagination
          v-if="totalPages > 1"
          :current-page="currentPage"
          :total-pages="totalPages"
          :total="totalItems"
          :page-size="pageSize"
          @update:current-page="handlePageChange"
        />
      </div>

      <!-- 创建/编辑对话框 -->
      <div
        v-if="showDialog"
        class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4"
        @click.self="closeDialog"
      >
        <div class="bg-white dark:bg-gray-800 rounded-lg p-6 max-w-2xl w-full">
          <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">
            {{ isEditing ? '编辑分类' : '添加分类' }}
          </h2>

          <form @submit.prevent="saveCategory" class="space-y-4">
            <!-- 基本信息 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  分类名称 *
                </label>
                <input
                  v-model="formData.name"
                  type="text"
                  required
                  class="input"
                  placeholder="例如：AI工具"
                />
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                  标识符 (Slug) *
                </label>
                <input
                  v-model="formData.slug"
                  type="text"
                  required
                  class="input"
                  placeholder="例如：ai-tools"
                />
              </div>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                图标 (Heroicons)
              </label>
              <input
                v-model="formData.icon"
                type="text"
                class="input"
                placeholder="例如：heroicons:sparkles"
              />
              <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                访问 <a href="https://heroicons.com/" target="_blank" class="text-primary-600 hover:underline">heroicons.com</a> 查找图标，格式：heroicons:图标名
              </p>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                描述
              </label>
              <textarea
                v-model="formData.description"
                rows="3"
                class="input"
                placeholder="分类描述"
              ></textarea>
            </div>

            <div>
              <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                排序
              </label>
              <input
                v-model.number="formData.sortOrder"
                type="number"
                min="0"
                class="input"
                placeholder="数字越小越靠前"
              />
            </div>

            <!-- 操作按钮 -->
            <div class="flex justify-end gap-4 pt-4">
              <button
                type="button"
                @click="closeDialog"
                class="btn btn-secondary"
              >
                取消
              </button>
              <button
                type="submit"
                class="btn btn-primary"
                :disabled="saving"
              >
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
  </div>
</template>

<script setup lang="ts">
import type { Category } from '~/types'

definePageMeta({
  layout: 'admin',
  middleware: ['auth'],
})

const { $api } = useNuxtApp()
const toast = useToast()

// 数据状态
const categories = ref<Category[]>([])
const showDialog = ref(false)
const isEditing = ref(false)
const saving = ref(false)

// 分页
const currentPage = ref(1)
const pageSize = ref(20)
const totalItems = ref(0)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

// 表单数据
const formData = ref<{
  name: string
  slug: string
  icon: string
  description: string
  sortOrder: number
}>({
  name: '',
  slug: '',
  icon: '',
  description: '',
  sortOrder: 0,
})

const currentCategory = ref<Category | null>(null)

// 获取分类列表
const fetchCategories = async () => {
  try {
    const data = await $api<Category[]>('/categories')
    categories.value = data.sort((a, b) => (a.sortOrder || 0) - (b.sortOrder || 0))
    totalItems.value = data.length
  } catch (error: any) {
    toast.error(error.message || '获取分类列表失败')
  }
}

// 打开创建对话框
const openCreateDialog = () => {
  isEditing.value = false
  formData.value = {
    name: '',
    slug: '',
    icon: 'heroicons:folder',
    description: '',
    sortOrder: categories.value.length + 1,
  }
  showDialog.value = true
}

// 打开编辑对话框
const openEditDialog = (category: Category) => {
  isEditing.value = true
  currentCategory.value = category
  formData.value = {
    name: category.name,
    slug: category.slug,
    icon: category.icon || '',
    description: category.description || '',
    sortOrder: category.sortOrder || 0,
  }
  showDialog.value = true
}

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false
  currentCategory.value = null
}

// 保存分类
const saveCategory = async () => {
  saving.value = true
  try {
    if (isEditing.value && currentCategory.value) {
      // 更新
      await $api(`/categories/${currentCategory.value.id}`, {
        method: 'PATCH',
        body: formData.value,
      })
      toast.success('分类更新成功')
    } else {
      // 创建
      await $api('/categories', {
        method: 'POST',
        body: formData.value,
      })
      toast.success('分类创建成功')
    }
    closeDialog()
    await fetchCategories()
  } catch (error: any) {
    toast.error(error.message || '操作失败')
  } finally {
    saving.value = false
  }
}

// 删除分类
const deleteCategory = async (category: Category) => {
  if (!confirm(`确定要删除分类"${category.name}"吗？`)) {
    return
  }

  try {
    await $api(`/categories/${category.id}`, {
      method: 'DELETE',
    })
    toast.success('分类删除成功')
    await fetchCategories()
  } catch (error: any) {
    toast.error(error.message || '删除失败')
  }
}

// 处理翻页
const handlePageChange = (page: number) => {
  currentPage.value = page
  // 如果是真实分页，这里需要重新请求数据
  // await fetchCategories()
}

// 初始化
onMounted(() => {
  fetchCategories()
})
</script>

